package com.ken.mqbase.returnlistener;

import com.ken.constant.RabbitConstant;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * return机制 生产者
 * Created by renchongyu on 2018/11/15.
 */
public class ProductReturn {

    public static void main(String[] args) throws Exception{
        //1.创建一个ConnectionFactory
        ConnectionFactory conn = new ConnectionFactory();
        conn.setHost(RabbitConstant.RABBITMQ_IP);
        conn.setPort(RabbitConstant.RABBITMQ_PORT);
        conn.setUsername(RabbitConstant.RABBITMQ_USER_NAME);
        conn.setPassword(RabbitConstant.RABBITMQ_USER_PASSWORD);
        conn.setVirtualHost(RabbitConstant.RABBITMQ_VIRTUAL_HOST);

        //2.通过连接工厂连接
        Connection connection = conn.newConnection();

        //3.通过连接创建一个channel
        Channel channel = connection.createChannel();

        String exchange = "test_return_exchange";
        String routingKey = "return.save";
        String toutingKeyError = "abc.save";

        String msg = "Hello RabbitMQ from Ken's to return";

        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties basicProperties, byte[] body) throws IOException {
                System.out.println(replyCode);
                System.out.println(replyText);
                System.out.println(exchange);
                System.out.println(routingKey);
                System.out.println(basicProperties);
                System.out.println(new String(body));
            }
        });
        channel.basicPublish(exchange,toutingKeyError,true,null,msg.getBytes());
    }
}
